package com.gzmu.face.controller;

import com.gzmu.face.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
	@RequestMapping("/login")
	public Map<String, Object> login(User user, BindingResult bindingResult) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 1、JSR303
		if (bindingResult.hasErrors()) {
			map.put("code", 0);
			map.put("errorInfo", bindingResult.getFieldError().getDefaultMessage());
			return map;
		}
		// 2、Shiro
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getName(), user.getPasswd());
		try {
			subject.login(token);
			map.put("code", 200);
			map.put("errorInfo", "登录成功!");
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", 1);
			map.put("errorInfo", "用户名或者密码错误!");
			return map;
		}
	}
}
